<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\api\permissions;

use App\Common\Repositories\System\CustomerDepartmentsRepository;
use App\Exception\AppException;
use xsl\basic\BaseController;
use xsl\enums\Code;

class Departments extends BaseController
{
    protected $repository;

    public function __construct(CustomerDepartmentsRepository $repository)
    {
        $this->repository = $repository;
    }

    public function index()
    {
        $where = $this->request->all();
        $list = $this->repository->getWhereList(['*'], $where);
        return $this->success($list);
    }

    public function create()
    {
        $params = $this->request->all();
        return $this->success($this->repository->create($this->tmpData($params)));
    }

    public function enable($id)
    {
        try {
            return $this->success($this->repository->toggleBy($id));
        } catch (AppException $e) {
            return $this->error($e->getMessage(), $e->getCode());
        }
    }

    public function delete($id)
    {
        if ($this->repository->existsWhere(['parent_id' => $id])) {
            return $this->error('存在下级', Code::FAILED);
        }
        return $this->success($this->repository->delete($id));
    }

    public function read($id)
    {
        return $this->success($this->repository->get($id));
    }

    public function update($id)
    {
        $params = $this->request->all();
        return $this->success($this->repository->update($id, $this->tmpData($params)));
    }

    public function tmpData($params)
    {
        $data = [];
        $data['parent_id'] = $params['parent_id'] ?? 0;
        $data['department_name'] = $params['department_name'] ?? '';
        $data['principal'] = $params['principal'] ?? '';
        $data['mobile'] = $params['mobile'] ?? '';
        $data['email'] = $params['email'] ?? '';
        $data['sort'] = $params['sort'] ?? '';
        $data['creator_id'] = $this->request->adminId();
        return $data;
    }
}
